﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Extentions;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class ProceedsController : BaseController
	{
		/// <summary>
		/// 收款统计分析页面
		/// </summary>
		/// <returns></returns>
		public ActionResult Statistic()
		{
			return View();
		}

		/// <summary>
		/// 年度收款组成分布统计
		/// </summary>
		public ActionResult Gather1(int year)
		{
			var query = (from q in Db.PayeeRecords
			             where q.Year == year
			             group q by q.PayerType
			             into g
			             select new
			                    {
				                    PayerType = g.Key,
				                    Amount = g.Sum(x => x.Amount)
			                    }).ToList().OrderBy(x => x.PayerType);

			return J(new
			         {
				         PieData = query.Select(x => x.Amount).ToList(),
				         PieLegend = query.Select(x => string.Format("%%.%%({0:C0}) —— {1}", x.Amount, ((PayerTypes) x.PayerType).ToDescription()))
			         });
		}

		/// <summary>
		/// 全年收款趋势分析
		/// </summary>
		public ActionResult Gather2(int year)
		{
			var query = (from q in Db.PayeeRecords
			             where q.Year == year
			             group q by new
			                        {
				                        q.PayerType,
				                        q.Month
			                        }
			             into g
			             select new
			                    {
				                    g.Key.PayerType,
				                    g.Key.Month,
				                    Amount = g.Sum(x => x.Amount)
			                    }).ToList();

			var payerTypes = query.Select(x => x.PayerType).Distinct().OrderBy(x => x).ToList();
			var chartData = new List<List<decimal>>();
			var legend = new List<string>();
			foreach (var pt in payerTypes)
			{
				var source = query.Where(x => x.PayerType == pt).ToList();
				var data = new List<decimal>();
				for (var i = 1; i <= 12; ++i)
				{
					var item = source.FirstOrDefault(x => x.Month == i);
					data.Add(item==null?0:item.Amount);
				}

				chartData.Add(data);
				legend.Add(((PayerTypes) pt).ToDescription());
			}

			return J(new
			         {
				         ChartData = chartData,
				         Legend = legend
			         });
		}
	}
}